package com.lk.controller;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 用户
 *
 * @author 薄一鸣
 * @date 2024/7/23 13:54
 * @version V1.0
 */

@RestController
public class UserController {

    @Autowired
    RestHighLevelClient client;

    public static final String USER_INDEX = "users";

    public static Map<String, Object> loginUsers = new HashMap<>();

    /**
     *  用户登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public Map login(@RequestBody Map<String, String> map) {
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> sourceAsMap = null;
        try {
            String username = map.get("username");
            String password = map.get("password");

            SearchRequest searchRequest = new SearchRequest(USER_INDEX);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            // 构建 Term 查询
            searchSourceBuilder.query(QueryBuilders.termQuery("username", username));


            searchRequest.source(searchSourceBuilder);
            List list = new ArrayList();
            // 执行搜索

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] searchHits = searchResponse.getHits().getHits();
            if (searchHits.length == 0) {
                throw new Exception("用户名或密码错误");
            }
            sourceAsMap = searchHits[0].getSourceAsMap(); // 获取解析后的 Map

            password = DigestUtils.md5Hex(password);

            // 判断用户名密码
            if (!password.equals(sourceAsMap.get("password"))) {
                throw new Exception("用户名或密码错误");
            }


        } catch (Exception e) {
            res.put("code", "10001");
            res.put("msg", "登录失败");
            res.put("token", "");
            return res;
        }

        String token = UUID.randomUUID().toString();
        loginUser(token,sourceAsMap);
        res.put("code", "0");
        res.put("msg", "登录成功");
        res.put("token", token);
        return res;
    }

    /**
     * 密码修改
     * @param map
     * @return
     */
    @PostMapping("/resetPassword")
    public Map resetPassword(@RequestBody Map<String, String> map) {
        Map<String, Object> res = new HashMap<>();
        try {
            String username = map.get("username");
            String password = map.get("password");

            SearchRequest searchRequest = new SearchRequest(USER_INDEX);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            // 构建 Term 查询
            searchSourceBuilder.query(QueryBuilders.termQuery("username", username));


            searchRequest.source(searchSourceBuilder);
            List list = new ArrayList();
            // 执行搜索

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] searchHits = searchResponse.getHits().getHits();

            Map<String, Object> sourceAsMap = searchHits[0].getSourceAsMap(); // 获取解析后的 Map
            String id = searchHits[0].getId();

            String md5Hex = DigestUtils.md5Hex(password);
            map.put("password", md5Hex);

            UpdateRequest updateRequest = new UpdateRequest(
                    USER_INDEX, // 索引名
                    "_doc",
                    id         // 文档ID
            );
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            updateRequest.doc(JSONObject.toJSONString(map), XContentType.JSON);

        } catch (Exception e) {
            res.put("code", "10002");
            res.put("msg", "用户不存在");
            res.put("token", "");
            return res;
        }

        String token = UUID.randomUUID().toString();
        res.put("code", "0");
        res.put("msg", "修改成功");
        res.put("token", token);
        return res;
    }

    /**
     * 用户登录
     *
     * @param token
     * @param map
     */
    public void loginUser(String token,Map<String,Object> map){
        loginUsers.put(token,map);
    }

    /**
     * 验证用户是否登录
     *
     * @param token
     */
    public boolean auth(String token){
        if(loginUsers.get(token) !=null ){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String md5Hex = DigestUtils.md5Hex("admin");
        System.out.println(md5Hex);
    }
}

